package managedbean;

import entity.SalesForecastToActualSalesEntity;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import javax.faces.bean.SessionScoped;
import type.Month;
/**
 *
 * @author thanhle
 */
@ManagedBean(name = "jasper")
@SessionScoped
public class Jasper {

    @Resource(name = "macteamData")
    private DataSource macteamData;
    private String fileName;
    @EJB
    private bean.session.SalesForecastEntityFacade forecastFacade;
    
    //if list supplier report exist
    private boolean exist = false;

    public boolean isExist() {
        return exist;
    }

    public void setExist(boolean exist) {
        this.exist = exist;
    }
    //if list raw material exist
     private boolean exist1 = false;
//     @PersistenceContext(unitName = "MacTeam-warPU")
//    private EntityManager em;

    public boolean isExist1() {
        return exist1;
    }

    public void setExist1(boolean exist1) {
        this.exist1 = exist1;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void generateSupplierReport() throws ClassNotFoundException, SQLException, IOException, JRException {

        Connection conn = null;
        JasperReport jasperreport;
        JasperPrint jasperprint;

        try {
            conn = macteamData.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(ExportToPDFBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {

            String home_path = System.getProperty("user.home");

            if (home_path.indexOf("\\") > 0) {

                path = home_path + "\\report6.pdf";

            } else {
                path = home_path + "/report6.pdf";
            }

            File f = new File(path);
            setFileName("Supplier.pdf");
            setPath(path);
            boolean success = false;
            if (f.exists()) {
                success = f.delete();
            }


            String sql = "SELECT rawmaterial.PRODUCTNAME AS PRODUCTNAME,vendor.COMPANYNAME AS COMPANYNAME,vendor.NAME AS REPRESENTATIVE,contact.CONTACTNUMBER AS CONTACTNUMBER FROM `rawmaterial` rawmaterial INNER JOIN `rawmaterial_vendor` rawmaterial_vendor ON rawmaterial.`ID` = rawmaterial_vendor.`rms_ID`"
                    + " INNER JOIN `vendor` vendor ON rawmaterial_vendor.`vendor_ID` = vendor.`ID`,`contact` contact Where vendor.LOCKED =FALSE AND contact.PERSON_ID = vendor.ID ORDER BY rawmaterial.PRODUCTNAME";
            FacesContext context = FacesContext.getCurrentInstance();
            ResultSet rsEvents = macteamData.getConnection().prepareStatement(sql).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsEvents);
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

            InputStream reportStream1 = context.getExternalContext().getResourceAsStream("/jasperreports/report6.jrxml");
            HashMap parameters = new HashMap();

            JasperDesign jd1;

            jd1 = JRXmlLoader.load(reportStream1);
            jasperreport = JasperCompileManager.compileReport(jd1);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperreport, parameters, conn);
            JasperExportManager.exportReportToPdfFile(jasperPrint, path);


            context.responseComplete();



            FacesContext context1 = FacesContext.getCurrentInstance();
            InputStream reportStream = context1.getExternalContext().getResourceAsStream("/jasperreports/report6.jasper");
            response.setContentType("application/pdf");

            ServletOutputStream outputStream = response.getOutputStream();


            JasperRunManager.runReportToPdfStream(reportStream, outputStream, parameters, jrResultSetDataSource);

            outputStream.flush();
            outputStream.close();
            context1.responseComplete();
            exist = true;
        } catch (JRException jrex) {
            System.out.println("********** Jasperreport Exception");
            jrex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //  return "";
    }
    private Date startDate;

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    private Date endDate;

//            String sql = "SELECT rawmaterial.`PRODUCTNAME` AS PRODUCT, vendor.`COMPANYNAME` AS COMPANY, rawmaterialpurchaseorder.`QUANTITY` AS QUANTITY, rawmaterialpurchaseorder.`DATECONFIRMED` AS DATECONFIRMED, rawmaterialpurchaseorder.`COST` AS COST"
//                    + " FROM `vendor` vendor INNER JOIN `vendor_rawmaterialpurchaseorder` vendor_rawmaterialpurchaseorder ON vendor.`ID` = vendor_rawmaterialpurchaseorder.`Vendor_ID` INNER JOIN `rawmaterialpurchaseorder` rawmaterialpurchaseorder ON vendor_rawmaterialpurchaseorder.`rawMaterialPurchases_ID` = rawmaterialpurchaseorder.`ID` INNER JOIN `rawmaterialquotation` rawmaterialquotation ON rawmaterialpurchaseorder.`RMQ_ID` = rawmaterialquotation.`ID`"
//                    + " INNER JOIN `rawmaterial` rawmaterial ON rawmaterialquotation.`RAWMATERIAL_ID` = rawmaterial.`ID` where rawmaterialpurchaseorder.DATECONFIRMED BETWEEN $P{startDate} AND $P{endDate} AND rawmaterialpurchaseorder.STATUS = 3";
    public void generateRawPurchasingReport() throws ClassNotFoundException, SQLException, IOException, JRException {

        Connection conn = null;
        JasperReport jasperreport;
        JasperPrint jasperprint;

        try {
            conn = macteamData.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(ExportToPDFBean.class.getName()).log(Level.SEVERE, null, ex);
        }


        try {
//            ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
//            //delete existing file
//            String name = "/download/report7.pdf";
            String home_path = System.getProperty("user.home");
            if (home_path.indexOf("\\") > 0) {
                System.out.println("DADSDSA");
                path = home_path + "\\report7.pdf";
                System.out.println(path + "hhh");
            } else {
                path = home_path + "/report7.pdf";
            }
            File f = new File(path);
            setPath(path);
            setFileName("OrderReport.pdf");
            boolean success = false;
            if (f.exists()) {
                success = f.delete();
            }

            //compile the report
            Connection connection;
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            InputStream reportStream1 = context.getExternalContext().
                    getResourceAsStream("/jasperreports/report7.jrxml");


            HashMap parameters = new HashMap();
            parameters.put("startDate", getStartDate());


            parameters.put("endDate", getEndDate());
            JasperDesign jd1;

            jd1 = JRXmlLoader.load(reportStream1);
            jasperreport = JasperCompileManager.compileReport(jd1);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperreport, parameters, conn);
            JasperExportManager.exportReportToPdfFile(jasperPrint, path);



            context.responseComplete();



            //output the report
            FacesContext context1 = FacesContext.getCurrentInstance();

            ServletOutputStream servletOutputStream =
                    response.getOutputStream();
            InputStream reportStream = context1.getExternalContext().getResourceAsStream("/jasperreports/report7.jasper");


            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters, conn);


            response.setContentType("application/pdf");
            servletOutputStream.flush();
            servletOutputStream.close();
            context1.responseComplete();
            exist1 = true;
        } catch (JRException jrex) {

            jrex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    public void generateInventoryReport() throws ClassNotFoundException, SQLException, IOException, JRException {

        Connection conn = null;
        JasperReport jasperreport;
        JasperPrint jasperprint;

        try {
            conn = macteamData.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(ExportToPDFBean.class.getName()).log(Level.SEVERE, null, ex);
        }


        try {
            String home_path = System.getProperty("user.home");
            if (home_path.indexOf("\\") > 0) {
                System.out.println("DADSDSA");
                path = home_path + "\\newtest.pdf";
                System.out.println(path + "hhh");
            } else {
                path = home_path + "/newtest.pdf";
            }
            File f = new File(path);
            setPath(path);
            setFileName("newtest.pdf");
            boolean success = false;
            if (f.exists()) {
                success = f.delete();
            }

            //compile the report
            Connection connection;
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            InputStream reportStream1 = context.getExternalContext().
                    getResourceAsStream("/jasperreports/newtest.jrxml");


            HashMap parameters = new HashMap();
            parameters.put("startDate", getStartDate());


            parameters.put("endDate", getEndDate());
            JasperDesign jd1;

            jd1 = JRXmlLoader.load(reportStream1);
            jasperreport = JasperCompileManager.compileReport(jd1);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperreport, parameters, conn);
            JasperExportManager.exportReportToPdfFile(jasperPrint, path);



            context.responseComplete();



            //output the report
            FacesContext context1 = FacesContext.getCurrentInstance();

            ServletOutputStream servletOutputStream = response.getOutputStream();

            InputStream reportStream = context1.getExternalContext().getResourceAsStream("/jasperreports/newtest.jasper");


            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters, conn);


            response.setContentType("application/pdf");
            servletOutputStream.flush();
            servletOutputStream.close();
            context1.responseComplete();

        } catch (JRException jrex) {

            jrex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    public void generateSalesForecastManagementReport() throws ClassNotFoundException, SQLException, IOException, JRException {
        System.out.println("i am here");
        ArrayList<SalesForecastToActualSalesEntity> compareList = new ArrayList<SalesForecastToActualSalesEntity>(5);


        Calendar cal = Calendar.getInstance();
        int currentYear = cal.get(Calendar.YEAR);
        int currentMonthNum = cal.get(Calendar.MONTH) + 1;
        System.out.println("current month num " + currentMonthNum);


        if (currentMonthNum >= 6) {
            for (int i = currentMonthNum - 6; i <= currentMonthNum - 1; i++) {
                SalesForecastToActualSalesEntity s = new SalesForecastToActualSalesEntity();
                s.setYear(currentYear);
                s.setMonth(i);
                s.setForecastedValue(forecastFacade.findSalesForecast(currentYear, Month.fromMonthNum(i)).getForecast());
                s.setActualValue(forecastFacade.findGrossSales(currentYear, Month.fromMonthNum(i)));
                s.setPercentageChange((s.getActualValue() - s.getForecastedValue()) / s.getForecastedValue());
                System.out.println("PercentageChange " + s.getPercentageChange());
                if (forecastFacade.findSalesForecastManagementReport(s) == null) {
                    forecastFacade.createForecastManagementReport(s);
                }
            }
        } else {
            for (int k = 1; k <= currentMonthNum; k++) {
                SalesForecastToActualSalesEntity s = new SalesForecastToActualSalesEntity();
                s.setYear(currentYear);
                s.setMonth(k);
                s.setForecastedValue(forecastFacade.findSalesForecast(currentYear, Month.fromMonthNum(k)).getForecast());
                s.setActualValue(forecastFacade.findGrossSales(currentYear, Month.fromMonthNum(k)));
                s.setPercentageChange((s.getActualValue() - s.getForecastedValue()) / s.getForecastedValue());
                if (forecastFacade.findSalesForecastManagementReport(s) == null) {
                    forecastFacade.createForecastManagementReport(s);
                }
            }
            for (int j = 12; j >= 7; j--) {
                SalesForecastToActualSalesEntity s = new SalesForecastToActualSalesEntity();
                s.setYear(currentYear);
                s.setMonth(j);
                s.setForecastedValue(forecastFacade.findSalesForecast(currentYear, Month.fromMonthNum(j)).getForecast());
                s.setActualValue(forecastFacade.findGrossSales(currentYear, Month.fromMonthNum(j)));
                s.setPercentageChange((s.getActualValue() - s.getForecastedValue()) / s.getForecastedValue());
                if (forecastFacade.findSalesForecastManagementReport(s) == null) {
                    forecastFacade.createForecastManagementReport(s);
                }
            }
        }



        Connection conn = null;
        JasperReport jasperreport;
        JasperPrint jasperprint;

        try {
            conn = macteamData.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(ExportToPDFBean.class.getName()).log(Level.SEVERE, null, ex);
        }


        try {
            String home_path = System.getProperty("user.home");
            if (home_path.indexOf("\\") > 0) {
                System.out.println("DADSDSA");
                path = home_path + "\\productionPlanning.pdf";
                System.out.println(path + "hhh");
            } else {
                path = home_path + "/productionPlanning.pdf";
            }
            File f = new File(path);
            setPath(path);
            setFileName("productionPlanning.pdf");
            boolean success = false;
            if (f.exists()) {
                success = f.delete();
            }

            //compile the report
            Connection connection;
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            InputStream reportStream1 = context.getExternalContext().
                    getResourceAsStream("/jasperreports/ProductionReport.jrxml");


            HashMap parameters = new HashMap();
            parameters.put("startDate", getStartDate());


            parameters.put("endDate", getEndDate());
            JasperDesign jd1;

            jd1 = JRXmlLoader.load(reportStream1);
            jasperreport = JasperCompileManager.compileReport(jd1);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperreport, parameters, conn);
            JasperExportManager.exportReportToPdfFile(jasperPrint, path);



            context.responseComplete();



            //output the report
            FacesContext context1 = FacesContext.getCurrentInstance();

            ServletOutputStream servletOutputStream =
                    response.getOutputStream();
            InputStream reportStream = context1.getExternalContext().getResourceAsStream("/jasperreports/ProductionReport.jasper");


            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters, conn);


            response.setContentType("application/pdf");
            servletOutputStream.flush();
            servletOutputStream.close();
            context1.responseComplete();

        } catch (JRException jrex) {

            jrex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    public void generateFinanceReport() throws ClassNotFoundException, SQLException, IOException, JRException {

        Connection conn = null;
        JasperReport jasperreport;
        JasperPrint jasperprint;

        try {
            conn = macteamData.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(ExportToPDFBean.class.getName()).log(Level.SEVERE, null, ex);
        }


        try {
            String home_path = System.getProperty("user.home");
            if (home_path.indexOf("\\") > 0) {
                System.out.println("DADSDSA");
                path = home_path + "\\financeReport.pdf";
                System.out.println(path + "hhh");
            } else {
                path = home_path + "/financeReport.pdf";
            }
            File f = new File(path);
            setPath(path);
            setFileName("financeReport.pdf");
            boolean success = false;
            if (f.exists()) {
                success = f.delete();
            }

            //compile the report
            Connection connection;
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            InputStream reportStream1 = context.getExternalContext().
                    getResourceAsStream("/jasperreports/financeReport.jrxml");


            HashMap parameters = new HashMap();
            parameters.put("startDate", getStartDate());


            parameters.put("endDate", getEndDate());
            JasperDesign jd1;

            jd1 = JRXmlLoader.load(reportStream1);
            jasperreport = JasperCompileManager.compileReport(jd1);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperreport, parameters, conn);
            JasperExportManager.exportReportToPdfFile(jasperPrint, path);



            context.responseComplete();



            //output the report
            FacesContext context1 = FacesContext.getCurrentInstance();

            ServletOutputStream servletOutputStream = response.getOutputStream();

            InputStream reportStream = context1.getExternalContext().getResourceAsStream("/jasperreports/financeReport.jasper");


            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters, conn);


            response.setContentType("application/pdf");
            servletOutputStream.flush();
            servletOutputStream.close();
            context1.responseComplete();

        } catch (JRException jrex) {

            jrex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }
}
